package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.*;
import cn.com.hhrcw.message.MechanismService;
import cn.com.hhrcw.message.entity.DepartResult;
import cn.com.hhrcw.message.entity.UserResult;
import cn.com.hhrcw.service.*;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * @description:
 * @author: guojinfa
 * @time: 2020/12/1 16:49
 */
@RestController
@Slf4j
@RequestMapping("/admin/mechanism")
@Validated
public class MechanismController {
    @Autowired
    private IPiInfoService piInfoService;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private ISysUserDepartService sysUserDepartService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private MechanismService mechanismService;

    @Autowired
    private MySysUserRoleService sysUserRoleService;

    /**
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getUserList", method = RequestMethod.POST)
    public Result<?> getUserList(HttpServletRequest request,
                                 HttpServletResponse response) throws ExecutionException, InterruptedException {

        ThreadUtil.execute(
            () -> {

                log.info("开始同步同事");
                List<DepartResult> result = mechanismService.getDepartResult();

                if (CollectionUtils.isNotEmpty(result)) {
                    for (DepartResult departResult : result) {
                        String id = departResult.getId();
                        String pid = departResult.getPid();
                        String orgKey = departResult.getAffil_Uniq_Org_Key();
                        if (StrUtil.isNotBlank(orgKey)) {
                            if ("MDM_H_2722".equals(orgKey)) {
                                SysDepart depart = sysDepartService.getById(id);
                                if (null == depart) {
                                    SysDepart sysDepart = new SysDepart();
                                    sysDepart.setId(id);
                                    sysDepart.setParentId(departResult.getPid());
                                    sysDepart.setDepartName(departResult.getName());
                                    sysDepart.setOrgCategory("1");
                                    sysDepart.setOrgCode("");
                                    sysDepart.setCreateBy("admin");
                                    sysDepart.setCreateTime(DateTime.now());
                                    sysDepart.setStatus(departResult.getData_Stat());
                                    sysDepartService.save(sysDepart);
                                } else {
                                    depart.setParentId(departResult.getPid());
                                    depart.setDepartName(departResult.getName());
                                    depart.setStatus(departResult.getData_Stat());
                                    depart.setUpdateBy("admin");
                                    depart.setUpdateTime(DateTime.now());
                                    sysDepartService.saveOrUpdate(depart);
                                }
                                List<UserResult> resultList = mechanismService.getUserResult(id);
                                if (CollectionUtils.isNotEmpty(resultList)) {
                                    for (UserResult user : resultList) {
                                        SysUser sysUser = userService.getById(user.getId());
                                        if (null == sysUser) {

                                            String userId = user.getId();
                                            String phone = user.getPhone();

                                            SysUserDepart query = new SysUserDepart();
                                            query.setDepId(id);
                                            query.setUserId(userId);
                                            sysUserDepartService.save(query);
                                            SysUser member = new SysUser();
                                            member.setId(userId);
                                            member.setUsername(user.getWorkno());
                                            member.setWorkNo(user.getWorkno());
                                            member.setRealname(user.getName());
                                            member.setPost(user.getProfes_Post_Dsc());
                                            if (StringUtils.isBlank(phone)) {

                                                member.setPhone(user.getWorkno() + "@admin");
                                            } else {
                                                LambdaUpdateWrapper<SysUser> wrapper = Wrappers.lambdaUpdate();
                                                wrapper.eq(SysUser::getPhone, phone + "@admin");
                                                SysUser serviceOne = userService.getOne(wrapper);
                                                if (null != serviceOne) {
                                                    member.setPhone(phone + "（已重复）" + user.getWorkno() + "@admin");
                                                } else {
                                                    member.setPhone(phone + "@admin");
                                                }

                                            }
                                            String salt = RandomStringUtils.randomAlphanumeric(8);
                                            member.setSalt(salt);
                                            member.setPassword(PasswordUtil.encrypt(member.getUsername(), salt, member.getSalt()));
                                            member.setDelFlag(false);
                                            Integer state = Convert.toInt(user.getState());
                                            member.setStatus(state == null ? 1 : state);
                                            userService.saveOrUpdate(member);
                                            PiInfo piInfo = new PiInfo();
                                            piInfo.setId(userId);
                                            piInfo.setUserId(userId);
                                            piInfo.setPhone(member.getPhone());
                                            piInfo.setUsername(member.getUsername());
                                            piInfo.setCreateTime(DateTime.now());
                                            piInfo.setCreateBy(userId);
                                            piInfo.setDelFlag(false);
                                            piInfo.setIdNumber(user.getCertificateNum());
                                            piInfo.setRoleType("2,");
                                            piInfo.setName(user.getName());
                                            piInfo.setStationName(user.getProfes_Post_Dsc());
                                            if (StrUtil.isNotBlank(user.getGender())) {
                                                piInfo.setSex(Integer.valueOf(user.getGender()));
                                            } else {
                                                piInfo.setSex(0);
                                            }

                                            piInfo.setPhotoId("");
                                            piInfoService.saveOrUpdate(piInfo);
                                            SysUserRole sysUserRole = new SysUserRole();
                                            sysUserRole.setUserId(userId);
                                            sysUserRole.setRoleId("f6817f48af4fb3af11b9e8bf182f618b");
                                            sysUserRoleService.save(sysUserRole);
                                        } else {
                                            String phone = user.getPhone();
                                            sysUser.setUsername(user.getWorkno());
                                            sysUser.setWorkNo(user.getWorkno());
                                            sysUser.setPost(user.getProfes_Post_Dsc());
                                            sysUser.setRealname(user.getName());
                                            if (StringUtils.isBlank(phone)) {

                                                sysUser.setPhone(user.getWorkno() + "@admin");
                                            } else {
                                                sysUser.setPhone(phone + "@admin");
                                            }
                                            userService.saveOrUpdate(sysUser);
                                            PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, sysUser.getId())
                                                .eq(PiInfo::getDelFlag, false).one();
                                            if (piInfo != null) {
                                                piInfo.setPhone(sysUser.getPhone());
                                                piInfo.setUsername(sysUser.getUsername());
                                                piInfo.setName(sysUser.getRealname());
                                                piInfo.setStationName(user.getProfes_Post_Dsc());
                                                piInfoService.saveOrUpdate(piInfo);
                                            }

                                            List<SysUserRole> roles = sysUserRoleService.lambdaQuery().eq(SysUserRole::getUserId, piInfo.getUserId()).list();
                                            if (CollUtil.isEmpty(roles)) {
                                                SysUserRole sysUserRole = new SysUserRole();
                                                sysUserRole.setUserId(piInfo.getUserId());
                                                sysUserRole.setRoleId("f6817f48af4fb3af11b9e8bf182f618b");
                                                sysUserRoleService.save(sysUserRole);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }

                }
            }
        );
        return Result.ok();
    }

    private SysDepart toDepartVO(DepartResult departResult) {
        SysDepart sysDepart = new SysDepart();
        String id = departResult.getId();
        sysDepart.setId(id);
        sysDepart.setParentId(departResult.getPid());
        sysDepart.setDepartName(departResult.getName());
        sysDepart.setOrgCategory("1");
        sysDepart.setOrgCode("");
        sysDepart.setCreateBy("admin");
        sysDepart.setCreateTime(DateTime.now());
        sysDepart.setStatus(departResult.getData_Stat());
        return sysDepart;
    }
}
